<?php
class ImagesController extends ImagesAppController {

	var $name = 'Images';
	//var $helpers = array('Html', 'Form');
	var $helpers = array('Html', 'Form', 'Extend.GershImage', 'Extend.Lightbox');
	
	function index() {
		$this->redirect(array('/'));
	}
	function fetch($id) {
		if (!$id) {
			return "No images";
		}
		$this->Image->recursive = -1;
		return $this->Image->read(null, $id);
	}
	
	function admin_index() {
		$this->Image->recursive = 0;
		$this->set('images', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Image.', true));
			$this->redirect('/admin/images');
		}
		$this->set('image', $this->Image->read(null, $id));
	}
	function admin_create($data = null) {
		if($data != null) {
			$this->Image->create();
			if($data['Image']['title'] == "") {
				$data['Image']['title'] = trim($data['Image']['filename']['name']);
			}
			
			if ($this->Image->save($data)) {
				$this->Session->setFlash(__('The Image has been saved', true));
				return true;
			} else {
				$this->Session->setFlash(__('The Image could not be saved. Please, try again.', true));
				return false;
			}
			
				
		} else {
			return false;
		}
	}
	
	function admin_external_add() {
		if (!empty($this->data)) {
			if($this->admin_create($this->data)) {
				if(isset($this->data['Image']['return_url'])) {
					$this->redirect($this->data['Image']['return_url']);
				} else {
					$this->redirect('/admin/images');
				}
			}
		}
		
		$this->render('admin_add');
		//debug($this->data);
		
		
	}

	function admin_add() {
		//debug($this);
		if (!empty($this->data)) {
			if ($this->admin_create($this->data)) {
				$this->redirect('/admin/images');
			} 
		}
		//$posts = $this->Image->Post->find('list');
		//$this->set(compact('posts'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Image', true));
			$this->redirect('/admin/images');
		}
		if (!empty($this->data)) {
			if(!empty($this->data['Image']['order'])) {
				$this->data['Image']['order'] = 0;
			}
			if ($this->Image->save($this->data)) {
				$this->Session->setFlash(__('The Image has been saved', true));
				$this->data = $this->Image->read(null, $id);
				$this->redirect('/admin/images');
			} else {
				$this->Session->setFlash(__('The Image could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Image->read(null, $id);
		}
		//$posts = $this->Image->Post->find('list');
		//$this->set(compact('posts'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Image', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Image->del($id)) {
			$this->Session->setFlash(__('Image deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>